package com.ie.service.admin;

import cn.hutool.db.Page;
import cn.hutool.db.sql.Order;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.common.http.ResponseResult;
import com.ie.common.security.utils.JwtTokenUtil;
import com.ie.entity.BUserEntity;
import com.ie.entity.OrdersEntity;
import com.ie.mapper.admin.OrdersMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersEntity> implements OrdersService {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public ResponseResult<List<OrdersEntity>> getOrdersByUid(
            HttpServletRequest request,
            @RequestHeader("Authorization") String token) {
        LambdaQueryWrapper<OrdersEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        String jwtToken = token.substring(7);
        Integer uid = jwtTokenUtil.getUidFromJWT(jwtToken);
        System.out.println("解析后的 JWT Token: " + token);
        if(uid != null && uid != 0)
        {
            lambdaQueryWrapper.eq(OrdersEntity::getBusertableId, uid);
        }
        List<OrdersEntity> ordersEntities = list(lambdaQueryWrapper);
        return ResponseResult.getSuccessResult(ordersEntities);
    }

    @Override
    public ResponseResult<Map<String, Object>> submitOrder(OrdersEntity ordersEntity) {
        ordersEntity.setStatus(1);
        ordersEntity.setOrderdate(new Date());
        boolean result = save(ordersEntity);
        if(result){
            return ResponseResult.getMessageResult(null, "A001");
        } else {
            return ResponseResult.getMessageResult(null, "A002");
        }
    }
}
